const path = require('path')
const fs = require('fs')

/**
 *
 * @param entryPath 目录Path
 * @return {[dir.dir.fileNameWithoutExt]:{entry,template}}  返回一个文件字典
 */
function getFileEntries(entryPath) {
  const entries = {}
  traverseDir(entryPath, [], visitor)
  return entries
  // internal
  function visitor(dirent, dirPath, pathWay) {
    const fullName = path.join(dirPath, dirent.name)
    if (dirent.isDirectory()) {
      traverseDir(fullName, [...pathWay, dirent.name], visitor)
    } else if (path.extname(dirent.name) === '.html') {
      setEntries(parseEntryKey(fullName, pathWay), { template: fullName })
    } else if (path.extname(dirent.name) === '.js') {
      setEntries(parseEntryKey(fullName, pathWay), { entry: fullName })
    }
  }
  function parseEntryKey(name, pathWay) {
    return [...pathWay, path.parse(name).name].join('.')
  }
  function setEntries(key, val) {
    if (!entries[key]) {
      entries[key] = {}
    }
    Object.assign(entries[key], val)
  }
}
module.exports = {
  getFileEntries
}

// internal
function traverseDir(dirPath, options, visitor) {
  const items = fs.readdirSync(dirPath, { withFileTypes: true })
  for (const item of items) {
    visitor(item, dirPath, options)
  }
}
